import fs from "fs-extra";
import { logger } from "mcp-framework";
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export async function clearLog(clearTime: number) {
    const logDirPath = join(dirname(__dirname), '..', 'logs');

    if (!fs.existsSync(logDirPath)) {
        logger.info(`日志目录不存在: ${logDirPath}`);
        return;
    }

    const currentLogPath = logger.getLogPath();
    if (clearTime === 0) {
        const logDirs = fs.readdirSync(logDirPath);
        logDirs.forEach(async (dir) => {
            const delPath = join(logDirPath, dir);
            if (delPath === currentLogPath) {
                return;
            }
            fs.unlinkSync(delPath);
        });
        return;
    }
    const threeDaysAgo = Date.now() - clearTime * 24 * 60 * 60 * 1000;

    const logDirs = fs.readdirSync(logDirPath);
    logDirs.forEach(async (dir) => {
        const stat = fs.statSync(join(logDirPath, dir));
        if (stat.mtimeMs < threeDaysAgo) {
            fs.unlinkSync(join(logDirPath, dir));
        }
    });
}
